<template>
  <view class="st-u-moment-publish">
    <view class="st-flex-align-between" style="padding-top: 30rpx;padding-bottom: 40rpx;">
      <u-button size="mini" @click="saveLocal">保存草稿</u-button>
      <u-button type="success" size="mini" @click="publish" >确认发布</u-button>
    </view>
    <u-field
        v-model="content.content"
        type="textarea"
        :placeholder="contentPh"
        :clearable="false"
        :label-width="0"
        :focus="true"
    ></u-field>
    <u-upload ref="uUpload" :action="action" :file-list="content.fileList" :max-count="9" :form-data="{path: path}"></u-upload>
  </view>

</template>

<script>
/**
 * 该组件提供发布动态功能
 */
import MomentUrl from '../../../../pc/MomentUrl.js'
export default {
  props: {
    // 输入提示
    contentPh:{
      type: String,
      default: '这一刻您的想法...'
    },
    /**
     * 分组标识
     */
    groupFlag: {
      type: String
    },
    /**
     * 上传文件父级路径
     */
    path: {
      type: String,
      default: 'moment'
    }
  },
  data(){
    return {
      publishLoading: false,
      content: {
        content: '',
        fileList: []
      },
      action: this.$config.fileUploadUrl || '/file/cloudstorage/upload',

    }
  },
  mounted(){
    let saveLocal = uni.getStorageSync('momentLocal')
    if(saveLocal){
      this.content = saveLocal
    }
  },
  methods: {
    // 保存草稿
    saveLocal(){
      let urls = this.getAvailableUrls()
      if(!this.content.content && urls.length == 0){
        this.$u.toast('该写点什么呢')
        return
      }
      let data = {
        content: this.content.content,
        fileList: urls.map( item =>{return {url: item}})
      }
      uni.setStorageSync('momentLocal', data)
      this.$u.toast('保存成功')
      this.$emit('saveSuccess')
    },
    getAvailableUrls(){
      // 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
      let files = this.$refs.uUpload.lists.filter(val => {
        return val.progress == 100;
      })
      let r = []
      files.forEach((item,index) => {
        if (item.response) {
          r.push(item.response.url)
        }else {
          r.push(item.url)
        }
      })
      return r
    },
    // 发布
    publish(){

      let urls = this.getAvailableUrls()
      if(!this.content.content && urls.length == 0){
        this.$u.toast('该写点什么呢')
        return
      }
      let data = {content: this.content.content,groupFlag: this.groupFlag,momentPicUrls:urls}

      uni.showLoading({
        title: '发布中'
      });
      this.$http.post(MomentUrl.publish,data).then(res=>{
        this.$u.toast('发布成功')
        // 异步清除草稿
        uni.removeStorage({key: 'momentLocal'})
        this.$emit('publishSuccess',res.data)
      }).catch(error=>{
        this.$u.toast('发布失败，请稍候再试')
      }).finally(() => {
        uni.hideLoading();
      })
    }
  }
}
</script>

<style scoped>

</style>